<template>
  <el-card class="register-card">
    <h2 class="title">注册新账户</h2>
    <el-form ref="registerForm" :model="form" label-width="120px">
      <!-- 原有必填/可选字段（保持不变） -->
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="form.username"
          placeholder="2-16位字母/数字/下划线"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          type="password"
          v-model="form.password"
          placeholder="6-20位字母/数字组合"
        />
      </el-form-item>

      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          type="password"
          v-model="form.confirmPassword"
          placeholder="请重复输入密码"
        />
      </el-form-item>

      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="example@myblog.com" />
      </el-form-item>

      <!-- 可选字段 -->
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="form.nickname" placeholder="可选，2-10位字符" />
      </el-form-item>

      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="可选，如13812345678" />
      </el-form-item>

      <el-form-item label="个人网站" prop="website">
        <el-input
          v-model="form.website"
          placeholder="可选，如https://myblog.com"
        />
      </el-form-item>

      <el-form-item label="个人简介" prop="bio">
        <el-input
          type="textarea"
          v-model="form.bio"
          placeholder="可选，最多200字"
          rows="3"
        />
      </el-form-item>

      <!-- 头像上传（关键修改：补充 action 和 auto-upload） -->
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="handleBeforeAvatarUpload"
          :on-change="handleAvatarChange"
          accept="image/jpeg, image/png, image/gif"
          action="#"
          :auto-upload="false"
        >
          <img
            v-if="form.avatar"
            :src="form.avatar"
            class="avatar-preview"
            alt="头像预览"
          />
          <i v-else class="el-icon-plus avatar-placeholder"></i>
        </el-upload>
        <div v-if="form.avatar" class="avatar-tip">
          已选择头像（支持JPG/PNG/GIF）
        </div>
      </el-form-item>

      <!-- 原有注册按钮（保持不变） -->
      <el-form-item>
        <el-button type="primary" @click="handleRegister">立即注册</el-button>
        <el-link style="margin-left: 20px" @click="goLogin"
          >已有账号？去登录</el-link
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { postRegister } from "@/api";

export default {
  data() {
    return {
      form: {
        username: "",
        password: "",
        confirmPassword: "",
        email: "",
        nickname: "",
        phone: "",
        website: "",
        bio: "",
        avatar: null, // 新增：存储base64头像
      },
    };
  },
  methods: {
    // 新增：头像上传前校验
    handleBeforeAvatarUpload(file) {
      const isImage = ["image/jpeg", "image/png", "image/gif"].includes(
        file.type
      );
      const isLt2M = file.size / 1024 / 1024 <= 2;
      if (!isImage) {
        this.$message.error("仅支持JPG/PNG/GIF格式图片");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("图片大小不能超过2MB");
        return false;
      }
      return true;
    },

    // 新增：转换头像为base64并预览
    handleAvatarChange(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.form.avatar = e.target.result; // 存储base64字符串
      };
      reader.readAsDataURL(file.raw); // 转换为base64
    },

    async handleRegister() {
      console.log("开始提交注册请求...");

      // 移除：删除前端表单验证流程
      const submitData = {
        username: this.form.username,
        password: this.form.password,
        email: this.form.email,
        nickname: this.form.nickname || this.form.username,
        phone: this.form.phone || null,
        website: this.form.website || null,
        bio: this.form.bio || null,
        role: 0,
        avatar: this.form.avatar || null,
      };

      try {
        const res = await postRegister(submitData);
        console.log("接口响应:", res);

        if (res.data.status === 0) {
          this.$message.success("注册成功！即将跳转登录");
          setTimeout(() => this.$router.push("/login"), 1500);
        } else {
          this.$message.error(res.data.message || "注册失败，请重试");
        }
      } catch (err) {
        console.error("注册请求异常:", err);
        this.$message.error(
          `注册失败：${err.response?.data?.message || "网络异常"}`
        );
      }
    },
    goLogin() {
      this.$router.push("/login");
    },
  },
};
</script>

<style scoped>
.register-card {
  max-width: 600px; /* 增加宽度适配更多字段 */
  margin: 50px auto;
  padding: 30px 40px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
}

.el-form-item {
  margin-bottom: 18px; /* 调整字段间距 */
}

/* 新增头像样式 */
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 120px;
  height: 120px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}
.avatar-uploader:hover {
  border-color: #409eff;
}
.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.avatar-placeholder {
  font-size: 28px;
  color: #8c939d;
}
.avatar-tip {
  color: #606266;
  font-size: 12px;
  margin-top: 8px;
}
</style>
